﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using TodoUserV2.Data;
using TodoUserV2.Models;
using TodoUserV2.Data.Models;

namespace TodoUserV2.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            // NOT Implemented adapters....

            return View();
        }

        [Authorize]
        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";
            //
            // VM
           

            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                TodoIndexVm iVm = new TodoIndexVm();

                if (User.IsInRole("Admin"))
                {
                   
                    iVm.Greeting = "Hello Admin world...";

                    // grab all todos
                    //var q = db.Todos.AsQueryable();
                    var results = db.Todos.Select(a => new TodosVm { 
                    Task = a.Task,
                    User = db.Users.FirstOrDefault(u => u.Id == a.UserId)
                    }).ToList();
                    iVm.Todos = results; //db.Todos.ToList();
                    return View(iVm);
                }
                else
                {//grab todos for user
                    iVm.Greeting = "Hello Regular user world...";
                    var uId = User.Identity.GetUserId();
                    iVm.Todos = db.Todos.Where(t => t.UserId == uId).Select(a => new TodosVm{
                        Task = a.Task,
                        User = db.Users.FirstOrDefault(u => u.Id == uId)
                    }).ToList();
                    return View(iVm);
                }
            }
            
        }

        [ValidateAntiForgeryToken]
        [Authorize(Roles=Role.ADMIN)]
        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}